const {BrowserWindow, ipcMain, dialog, Menu } = require('electron');
const path = require('path')
const fs = require('fs')
const configTool = require('../tool/config')
const modTool = require('../tool/mod')
const fileTool = require('../tool/file')


let win
configTool.init()

let getConfig = (ent, key) => {
  return configTool.get(key)
}

let selectFile = async (ent, config) => {
  console.log(config)

  let defaultPath = configTool.get(config.setkey)
  if (defaultPath) {
    if (fileTool.isFile(defaultPath)) {
      defaultPath = path.dirname(defaultPath)
    } 
  }

  const { canceled, filePaths } = await dialog.showOpenDialog({
    title: config.title,
    properties: config.properties,
    defaultPath,
    filters: config.filters,
  })

  if (canceled) {
    return
  } 

  if (filePaths[0]) {
    configTool.set(config.setkey, filePaths[0]) 
  }
  return filePaths

}

let openSearchWin = (event, rs) => {
  // 创建子窗口  
  const childWindow = new BrowserWindow({  
    width: 1000,  
    height: 800,  
    parent: win, // 将子窗口设置为父窗口的子窗口  
    modal: true, // 设置为模态窗口，这样用户只能与子窗口交互  
    autoHideMenuBar: true,
    webPreferences: {  
      nodeIntegration: true // 如果需要使用 Node.js 特性，请启用此选项  
    }  
  })  

  // 加载 URL  
  childWindow.loadURL("https://www.wegame.com.cn/pc_game/assistant.html#/2000004/newMod/" + rs)  
  childWindow.webContents.on("dom-ready", ()=>{
    console.log("dom-ready")

    childWindow.webContents.executeJavaScript(
      `document.getElementsByClassName("widget-header")[0].style.display = 'none';`
      ).then((result) => {
      console.log(result) // Will be the JSON object from the fetch call
    })
  })


}

let setMod = async (event, indir, outdir, cover) => {
  let res = await modTool.search(win, indir, outdir, cover)
  console.log(res)
  return res
}

function createIndex () {
  Menu.setApplicationMenu(null)
  win = new BrowserWindow({
    width: 1000,
    height: 600,
    autoHideMenuBar: true,
    webPreferences: {
      preload: path.join(__dirname, '../preload/index.js')
    }
  })
  ipcMain.handle('selectFile', selectFile)
  ipcMain.handle('getConfig', getConfig)
  ipcMain.handle('openSearchWin', openSearchWin)
  ipcMain.handle('setMod', setMod)

   win.webContents.openDevTools()
   win.loadURL('http://localhost:3000/')
  //win.loadFile('dist/index.html')

}

module.exports = {
  createIndex
}
